<template>
  <div>
    <el-row class="el-tree-wrap" style="height:100%">
      <div v-show="!isHidden" style="width:225px;background-color: #fff; height: 100%;  border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);"  class="content " :class="{ 'hidden': isHidden}"
      :style="{ minHeight: minHeight }">
        <div style="position: relative;">
          <el-tree node-key="ID" :data="nodeData" :current-node-key="choseNode" :defaultExpandAll="defaultExpandAll" :highlight-current="true" :expand-on-click-node="false" :default-expanded-keys="expandArray"
            @node-click="handleNodeClick" :props="defaultProps" style="width:100%;height:calc(100vh - 80px)">
            <!-- slot-scope 来获取当前树节点的数据 (node)，并设置宽度为父容器的 90%。 -->
            <span slot-scope="{ node }" style="width: 90%;">
              <span class="blue-on-hover" style="display: flex; align-items: center;" @mouseover="node.data.edit = true" @mouseleave="node.data.edit = false">
                <div v-show="node.level === 1" style="width:100%;display: flex;justify-content: space-between;align-items: center;">
                  <span style="font-size:15px;font-family: Verdana;display:inline-block">{{ node.label }}</span>
                    <el-button type="text" style="padding-right:10px;" v-if="isEdit" @click.stop="addNew">{{`${dialogName}编辑`}}</el-button>
                    <span style="float:right;margin-right:15px;color: #c2c2c2;" v-show="!node.data.edit && !addTemplate">
                      {{ node.data.OnlineCount }} / {{ node.data.OnlineCount + node.data.OffLineCount }}
                    </span>
                </div>
                <div v-show="node.level > 1" style="align-items: center;justify-content: space-between;width: 100%;font-size:14px">
                  <span style="width: 7px;height: 7px;border-radius: 50%;background-color: #e5e5e5;display: inline-block;margin-right: 5px;"></span>
                  <el-tooltip effect="dark" :content="node.label" placement="left" v-show="node.label.length > 5" style="display:inline-block">
                    <span class="ellipsis">{{ node.label }}</span>
                  </el-tooltip>
                  <span v-show="node.label.length <= 5">{{ node.label }}</span>
                  <span style="float:right;margin-right:15px;color: #c2c2c2;" >
                    {{ node.data.Count }}
                  </span>
                </div>
              </span>
            </span>
            <span></span>
          </el-tree>
        </div>
      </div>
    </el-row>
    <div class="ssb-eh__close" v-show="!isHidden">
      <i class="el-icon-arrow-left" @click.stop="toggleVisibility"/>
    </div>
    <div class="ssb-eh__close" v-show="isHidden">
      <i class="el-icon-arrow-right" @click.stop="toggleVisibility"/>
    </div>
    <el-dialog 
      :close-on-click-modal="false" 
      :close-on-press-escape="false" 
      :title="`${dialogName}编辑`"
      :visible.sync="moderVisible"
      v-el-drag-dialog  
      width="30%">
      <el-form label-width="120px" :rules="rules" :model="partition" ref="partition">
        <div class="top-button" style="display:flex;">
          <el-button type="primary" icon="el-icon-plus" @click="addDepartment" size="mini">添加子{{ `${dialogName}` }}</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="modifyDepartment" size="mini" :disabled=" hasChildren || partition.ParentID === undefined" v-if="deepseek === 1">修改子{{ `${dialogName}` }}</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteDepartment" size="mini" :disabled=" hasChildren || partition.ParentID === undefined" v-if="FileName === 'xxx'">删除</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteDepartment2" size="mini" :disabled="!this.Name || hasChildren || hasCount" v-else>删除</el-button>
        </div>
        <el-divider class="dialog-category"></el-divider>
        <el-tree 
          node-key="ID" 
          :data="nodeData" 
          :current-node-key="choseNode" 
          :defaultExpandAll="defaultExpandAll" 
          :highlight-current="true" 
          :expand-on-click-node="false" 
          :default-expanded-keys="expandArray"
          :props="defaultProps" 
          @node-click="NodeClick" 
          style="width:100%;height:400px !important;overflow-y:auto;"
          >
          <span slot-scope="{ node }" style="width: 90%;">
            <span class="blue-on-hover" style="display: flex; align-items: center;">
              <div v-show="node.level === 1" style="width:100%;display: flex;justify-content: space-between;align-items: center;">
                <span style="font-size:15px;font-family: Verdana;display:inline-block">{{ node.label }}</span>
              </div>
              <div v-show="node.level > 1" style="align-items: center;justify-content: space-between;width: 100%;font-size:14px">
                <span style="width: 7px;height: 7px;border-radius: 50%;background-color: #e5e5e5;display: inline-block;margin-right: 5px;"></span>
                <el-tooltip effect="dark" :content="node.label" placement="left" v-show="node.label.length > 12" style="display:inline-block">
                  <span class="ellipsis">{{ node.label }}</span>
                </el-tooltip>
                <span v-show="node.label.length <= 12">{{ node.label }}</span>
              </div>
            </span>
          </span>
          <span></span>
        </el-tree>
      </el-form>
      <el-divider class="dialog-category"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="moderVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog 
      :close-on-click-modal="false" 
      :close-on-press-escape="false" 
      :title="Action === 1 ? `新增${dialogName}` : `修改${dialogName}`" 
      :visible.sync="departmentDialog"
      v-el-drag-dialog  
      width="30%">
      <el-form label-width="120px" :rules="rules" :model="partition" ref="partition">
        <el-form-item :label="`上级${dialogName}`" prop="ParentID">
          <el-cascader
            emitPath=false
            v-model="partition.ParentID"
            ref="cascaderAddr"
            :placeholder="`请选择上级${dialogName}`"
            :options="nodeData"
            :props="{children: 'Children', label: 'Name', value: 'ID', checkStrictly: true, emitPath: false, expandTrigger: 'hover'}" 
            clearable
            @visible-change="elCascaderOnlick"
            @expand-change="elCascaderOnlick" 
            @change="departmentChange"
            style="width: 100%;"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item :label="`${dialogName}名称`" prop="DepartmentName">
          <el-input :placeholder="`请输入${dialogName}名称`" maxlength="10" v-model="partition.DepartmentName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="departmentDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog 
      :close-on-click-modal="false" 
      :close-on-press-escape="false" 
      :title="Action === 1 ? `新增${dialogName}` : `修改${dialogName}`" 
      :visible.sync="departmentDialog2"
      v-el-drag-dialog  
      width="18%">
      <el-form label-width="120px" :rules="rules" :model="partition" ref="partition">
        <el-form-item :label="`${dialogName}名称`" prop="DepartmentName">
          <el-input :placeholder="`请输入${dialogName}名称`" maxlength="10" v-model="partition.DepartmentName"></el-input>
        </el-form-item>
        <el-form-item v-if="Action === 2" label="父类:" prop="ParentID">
            <el-select   v-model="partition.ParentID"  placeholder="请选择父类"  @change="handleSelectChange" :popper-class="color === 'night' ? 'nightClass' : ''">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!--   分割线与dialog-footer的间距 -->
    <el-divider class="lineToFooter"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit2()">确 定</el-button>
        <el-button type="info" @click="departmentDialog2 = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import draggable from 'vuedraggable'
import { getuuid } from '@/utils';
import {Material_URLS} from '@/views/Material/api/request';
import {noTokenRequest} from '@/api/material'
export default {
  directives: { elDragDialog },
  components: { draggable },
  props: {
    nodeData: {
      type: Array,
      default() {
        return []
      }
    },
    DepartmentList: {
      type: Array,
      default() {
        return []
      }
    },
    addTemplate: {
      type: Boolean,
      default() {
        return true
      }
    },
    minHeight: {
      type: String,
      default: 'calc(100vh - 70px)'
    },
    choseNode: {
      type: String,
      default() {
        return null
      }
    },
    defaultExpandAll: {
      type: Boolean,
      default() {
        return true
      }
    },
    isEdit: {
      type: Boolean,
      default() {
        return true
      }
    },
    expandArray:{
      type: Array,
      default() {
        return []
      }
    },
    defaultProps:{
      type: Object,
      default() {
        return {
          children: 'Children',
          label: 'Name',
          Count: 'Count'
        }
      }
    },
    dialogName:{
      type: String,
      default() {
        return '部门'
      }
    },
    FileName:{
      type: String,
      default() {
        return ''
      }
    },
    // 知识库的，@/view/Material/copoments/MateriialType.vue
    deepseek:{
      type: Number,
      default: 0
    },
    classList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  created() {
    
  },
  mounted() {
    this.color = localStorage.getItem("isNightMode")
  },
  data(){
    return {
      Action: 1,
      color: '',
      moderVisible: false,
      departmentDialog: false,
      departmentDialog2: false,
      isHidden: false,
      hasChildren: false,
      hasCount: false,
      Name: '',
      delID: '',
      modifyID: '',
      delParentName: '',
      options: '',
      KnowledgeIP: '',//知识库地址
      rules: {
        ParentID: [
          {required: true, message: '不能为空', trigger: 'change'}
        ],
        DepartmentName: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        Name: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ]
      },
      partition: {}
    }
  },
  methods: {
    handleNodeClick(data, node) {
      this.$emit('handleNodeClick', {data, node})
    },
    NodeClick(data, node){
      this.hasCount = data.Count === 0 ? false : true;
      this.hasChildren = data.children.length === 0 ? false : true;
      this.Name = data.Class
      this.delID = data.ParentID
      this.modifyID = data.ID
      this.delParentName = data.ParentName
      this.$set(this.partition, 'ParentID', data.ID || 0)
      this.$set(this.partition, 'ParentName', data.Class || "")
    },
     handleSelectChange(value) {
        // 找到选中的 option
        const selectedOption = this.options.find(item => item.value === value);
        if (selectedOption) {
          // 将 label 值赋给 partition.ParentName
          this.partition.ParentName = selectedOption.label;
        }
    },
    departmentChange(row){
      this.$set(this.partition, 'ParentID', row || 0)
      this.$set(this.partition, 'ParentName', this.DepartmentList.find(item => item.ID === row)?.Name || '')
    },
    addDepartment(){
      this.Action = 1
      // this.partition = {}
      if(this.FileName === ''){
        this.departmentDialog = true
      }else{
        this.departmentDialog2 = true
      }
    },
    modifyDepartment() {
      this.$set(this.partition, 'ParentID', "")
      const selectClass = this.classList.filter(item => item.Class !== this.partition.ParentName)
      
      // 2. 转换为 el-select 需要的 options 格式
      const options = selectClass.map(item => ({
        label: item.Class,  // 显示的名称（如 "分类1-2"）
        value: item.ID      // 对应的 ID（如 1744870363）
      }));

      // 3. 将 options 绑定到 el-select
      this.options = options;  // 确保在 data() 中定义了 options: []

      this.Action = 2
      this.departmentDialog2 = true
    },
    deleteDepartment(){
      this.$confirm(`此操作将永久删除该${this.dialogName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        
        if(this.deepseek === 1) {
          const data = {
            Action: 3,
            Class: {
            Class: this.Name,
            ParentName: this.delParentName,
            ID: this.partition.ParentID,
            ParentID: this.delID
            }
        }
      
        const res = await noTokenRequest(Material_URLS.editClassify,data)
        if(res.Status.StatusCode === 0){
                  this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.partition = {}
                this.$emit('addDepartment')
        }       
           
        }
        else {
          const data = {
          Data: {
            Action: 3,
            Detail: {
            Class: this.Name,
            ParentName: this.delParentName,
            ID: this.partition.ParentID,
            ParentID: this.delID
            }
          }
        }
        const res = await connrequest('EditDictKnowledgeClass', data)
        if (res.Status.StatusCode===0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.partition = {}
          this.$emit('addDepartment')
        }
        }
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    deleteDepartment2(){
      this.$confirm(`此操作将永久删除该${this.dialogName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: 3,
            Detail:{
              ClassID: this.Name
            }
          }
        }
        const res = await connrequest('EditDictKnowledgeClass', data)
        if (res.Status.StatusCode===0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.$emit('addDepartment')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    addNew(){
      if(this.deepseek === 1) {
        this.KnowledgeIP = localStorage.getItem("KnowledgeIP")
            if(!this.KnowledgeIP) {
                this.$message.error("请先配置知识库地址")
                return false;
            }
      }
      else {
        this.Action = 1
        this.partition = {},
        this.$nextTick(() => {
        this.$refs.partition.clearValidate();
      })
      }
      this.moderVisible = true
    },
    editItem(Name){
      this.Action = 2
      this.$set(this.partition, 'Name', Name)
      this.$nextTick(() => {
        this.$refs.partition.clearValidate();
      })
      this.moderVisible = true
    },
    deleteItem(node){
      this.$confirm(`此操作将永久删除该${this.dialogName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('deleteNode', node.data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    submit(){
      this.$refs['partition'].validate(async (valid) => {
        if (valid) {
          if(!this.partition.DepartmentName){
            this.$message.error(`请输入${this.dialogName}名称`)
            return false
          }
          const data = {
            Filter: {
              FileName: 'param_class_dict_URL.json'
            },
            Data: [
              ...this.DepartmentList,
              {
                ParentID: this.partition.ParentID || 0,
                ParentName: this.Name,
                Name: this.partition.DepartmentName,
                ID: Math.floor(Date.now() / 1000)
              }
            ]
          }
          const res = await connrequest('SetUICommonParam', data)
          if(res.Status.StatusCode === 0){
            this.$message.success(`新增${this.dialogName}成功`)
            this.departmentDialog = false
            this.$emit('addDepartment')
          }
        } else {
          return false;
        }
      })
    },
    submit2(){
      this.$refs['partition'].validate(async (valid) => {
        if (valid) {
          let arr = (this.nodeData[0].Children && this.nodeData[0].Children.length > 0) ? this.nodeData[0].Children : []
          let hastype = arr.findIndex(item => item.Name === this.partition.DepartmentName) !== -1
          if(hastype){
            this.$message.error(`该${this.dialogName}名称已经存在`)
            return false
          }
          if(!this.partition.DepartmentName){
            this.$message.error(`请输入${this.dialogName}名称`)
            return false
          }
          if(!this.partition.ParentID && !this.partition.ParentName) {
            this.$message.error("请先点击对话框对应的树结构再添加分类!")
            return false;
          }
        if(this.deepseek === 1) {
          if(this.Action === 1) {
          const data = {
              Action: 1,
              Class: {
                ID: Math.floor(Date.now() / 1000),
                Class: this.partition.DepartmentName,
                ParentID: this.partition.ParentID,
                ParentName: this.partition.ParentName
              }
          }
          const res = await noTokenRequest(Material_URLS.editClassify,data)
          if(res.Status.StatusCode === 0) {
                  this.$message.success(`新增${this.dialogName}成功`)
                  this.partition = {}
                  this.departmentDialog2 = false
                  this.$emit('addDepartment')
          }    
          }
          else {
            const data = {
                Action: 2,
                Class: {
                  ID: this.modifyID,
                  Class: this.partition.DepartmentName,
                  ParentID: this.partition.ParentID,
                  ParentName: this.partition.ParentName
                }
            }
            const res = await noTokenRequest(Material_URLS.editClassify,data)
            if(res.Status.StatusCode === 0) {
                    this.$message.success(`修改${this.dialogName}成功`)
                    this.departmentDialog2 = false
                    this.$emit('addDepartment')
            }    
            
          }
        }
        else {
          const data = {
            Data: {
              Action: 1,
              Detail: {
                ID: Math.floor(Date.now() / 1000),
                Class: this.partition.DepartmentName,
                ParentID: this.partition.ParentID,
                ParentName: this.partition.ParentName
              }
            }
          }
          const res = await connrequest('EditDictKnowledgeClass', data)
           if(res.Status.StatusCode === 0){
            this.$message.success(`新增${this.dialogName}成功`)
            this.partition = {}
            this.departmentDialog2 = false
            this.$emit('addDepartment')
          }
        }
          
          
        } else {
          return false;
        }
      })
    },
    toggleVisibility() {
      this.isHidden = !this.isHidden;
      this.$emit('toggleVisibility', this.isHidden)
    },
    elCascaderOnlick(){
        let that = this;
        setTimeout(function() {
            document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
            el.onclick = function() {
                this.previousElementSibling.click();
                that.$refs.cascaderAddr.dropDownVisible = false;
            };
            });
        }, 100);
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node__content{
  height: 38px;
  line-height: 38px;
  font-size: 15px;
}
.blue-on-hover:hover {
  color: #62bfff;
  /* cursor: pointer; */
}
.content {
  animation: fadeInOut 0.5s ease; /* 动画名称、持续时间、过渡曲线 */
  width: 240px; /* 初始状态 */
}
.hidden {
  animation: fadeInOut 0.5s ease; /* 动画名称、持续时间、过渡曲线 */
  width: 240px; /* 初始状态 */
}
@keyframes fadeInOut {
  0% {
    opacity: 240px; /* 起始状态 */
  }
  100% {
    opacity: 0px; /* 结束状态 */
  }
}
.ssb-eh__close {
  width: 20px;
  flex: 0 0 20px;
  text-align: center;
  line-height: 32px;
  background: #FFFFFF;
  box-shadow: 4px 0 16px 1px #3634651a;
  border-radius: 0 6px 6px 0;
  border: 1px solid #E5E5E5;
  border-left: none;
  cursor: pointer;
  color: #141414;
  top: 350px;
  left: 0px;
  height: 30px;
  position: absolute;
}
/* 限制文本宽度为 5 个字，超出部分显示省略号 */
.ellipsis {
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 12px;
  width: 5em !important; /* 一个汉字宽度约为 1em，可以根据需要调整宽度 */
}

::v-deep[class*=" el-icon-"],
[class^=el-icon-] {
  color: #141414 !important;
}
.top-button{
  padding-bottom: 30px;
}

</style>
